import axios from 'axios'
import NProgress  from 'nprogress'
import 'nprogress/nprogress.css'

const axiosInstance = axios.create({
	withCredentials: true
})

// 全局请求拦截
// 通过拦截器处理csrf问题，这里的正则和匹配下标可能需要根据实际情况小改动
axiosInstance.interceptors.request.use((config) => {
	NProgress.start()	//启动进度条
	//
	config.headers['X-Requested-With'] = 'XMLHttpRequest'
	const regex = /.*csrftoken=([^;.]*).*$/
	config.headers['X-CSRFToken'] = document.cookie.match(regex) === null ? null : document.cookie.match(regex)[1]
	return config
})

// 全局响应拦截
axiosInstance.interceptors.response.use(
	response => {
		NProgress.done()	// 关闭进度条
		return response
	},
	error => {
		NProgress.done()	// 关闭进度条
		return Promise.reject(error)
	}
)

export default axiosInstance